package test.m2.repositoryimpl;

import org.fornax.cartridges.sculptor.framework.accessapi.FindByKeyAccess;
import org.fornax.cartridges.sculptor.framework.accessapi.SaveAccess;
import org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByKeyAccessImpl;
import org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibSaveAccessImpl;

import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import test.m2.domain.X;
import test.m2.domain.XRepository;
import test.m2.exception.XNotFoundException;

/**
 * Repository implementation for X
 */
@Stateless(name = "xRepository")
public class XRepositoryBean implements XRepository {
    @PersistenceContext(unitName = "MyAppEntityManagerFactory")
    private EntityManager entityManager;

    public XRepositoryBean() {
    }

    /**
     * Delegates to {@link org.fornax.cartridges.sculptor.framework.accessapi.FindByKeyAccess}
     */
    public X findByKey(String name) throws XNotFoundException {
        FindByKeyAccess<X> ao = createFindByKeyAccess();

        ao.setKeyPropertyNames("name");
        ao.setKeyPropertyValues(name);

        ao.execute();

        if (ao.getResult() == null) {
            throw new XNotFoundException("No X found with name: " + name);
        }

        return ao.getResult();

    }

    /**
     * Delegates to {@link org.fornax.cartridges.sculptor.framework.accessapi.SaveAccess}
     */
    public X save(X entity) {
        SaveAccess<X> ao = createSaveAccess();

        ao.setEntity(entity);

        ao.execute();

        return ao.getResult();

    }

    /**
     * Dependency injection
     */
    @PersistenceContext(unitName = "MyAppEntityManagerFactory")
    protected void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    protected EntityManager getEntityManager() {
        return entityManager;
    }

    protected FindByKeyAccess<X> createFindByKeyAccess() {
        JpaHibFindByKeyAccessImpl<X> ao =
            new JpaHibFindByKeyAccessImpl<X>(getPersistentClass());

        ao.setEntityManager(getEntityManager());

        return ao;
    }

    protected SaveAccess<X> createSaveAccess() {
        JpaHibSaveAccessImpl<X> ao =
            new JpaHibSaveAccessImpl<X>(getPersistentClass());

        ao.setEntityManager(getEntityManager());

        return ao;
    }

    protected Class<X> getPersistentClass() {
        return X.class;
    }
}
